import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { REQUEST_USER_KEY } from '../../constants';
import { IS_PUBLIC_KEY } from 'src/common/decorators/public.decorator';
import { JwtService } from '@nestjs/jwt';
import { Reflector } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AccessTokenGuard implements CanActivate {
  constructor(
    private readonly jwtService: JwtService,
    private readonly reflector: Reflector,
    private readonly configService: ConfigService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.get(IS_PUBLIC_KEY, context.getHandler());
    if (isPublic) return true;
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      const options = {
        secret: this.configService.get<string>('jwt.secret'),
        audience: this.configService.get<string>('jwt.audience'),
        issuer: this.configService.get<string>('jwt.issuer'),
        expiresIn: this.configService.get<number>('jwt.expiresIn'),
      };
      const payload = await this.jwtService.verifyAsync(token, options);
      // console.log('payload:', payload);
      request[REQUEST_USER_KEY] = payload;
    } catch (error) {
      throw new UnauthorizedException();
    }
    return true;
  }
  private extractTokenFromHeader(request: Request): string | undefined {
    // console.log(
    //   ' src\\auth\\guards\\access-token.guard.ts',
    //   '请求头携带的token:',
    //   request.headers.xytoken,
    // );
    const token = request.headers.xytoken ?? undefined;
    return token as string;
  }
}
